import { Module } from 'vuex';
import api from '@/api';
import { workbenchTaskListState } from './types';
import { RootState } from '../../type';
const state: workbenchTaskListState = {
    scrollDisabled: false,
    query: {
        pageNum: 1,
        pageSize: 20,
        selectType: 'workbench',
        requestSystem: null
    },
    list: [],
    currSelectIndex: -1
};

type StateType = typeof state

const app: Module<StateType, RootState> = {
    namespaced: true,
    state,
    mutations: {
        SET_LIST: (state, payload) => {
            state.list = payload;
        },
        SET_SCROLLDISABLED: (state, payload) => {
            state.scrollDisabled = payload;
        },
        SET_QUERY: (state, payload) => {
            state.query = {
                ...state.query,
                ...payload
            };
        },
        SET_CURRSELECTINDEX: (state, payload) => {
            state.currSelectIndex = payload;
        }
    },
    actions: {
        async getList({ commit, state }, isRefresh = false) {
            if (state.scrollDisabled) {
                return;
            }
            commit('SET_SCROLLDISABLED', true);
            // 刷新值
            if (isRefresh) {
                let currSelectId: any = null;
                if (state.list.length && state.currSelectIndex >= 0) {
                    const target: any = state.list[state.currSelectIndex];
                    currSelectId = target.id;
                }

                const pageSize = state.query.pageNum * state.query.pageSize;
                const { success, moule } = await api.pmpRequestInfoModel.selectPage({
                    ...state.query,
                    pageNum: 1,
                    pageSize
                });
                if (success) {
                    commit('SET_LIST', [...moule]);
                    if (moule.length && state.currSelectIndex >= 0) {
                        const index: any = moule.findIndex((item) => item.id === currSelectId);
                        commit('SET_CURRSELECTINDEX', index);
                    }
                }
            } else {
                const { success, moule } = await api.pmpRequestInfoModel.selectPage(state.query);
                if (success) {
                    if (state.query.pageNum === 1) {
                        commit('SET_LIST', [...moule]);
                    } else {
                        commit('SET_LIST', [...state.list, ...moule]);
                    }
                    if (moule.length === state.query.pageSize) {
                        commit('SET_QUERY', {
                            pageNum: state.query.pageNum + 1
                        });
                        commit('SET_SCROLLDISABLED', false);
                    } else {
                        commit('SET_SCROLLDISABLED', true);
                    }
                }
            }
        }
    }
};

export default app;
